// @ts-ignore
import { useIntl } from 'umi';
// @ts-ignore
import { DefaultFooter } from '@ant-design/pro-layout';
import React, { useState } from 'react';
import { Button, Input,Image, List, message, Modal, Popconfirm, Space, Upload } from 'antd';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';

import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { useMount, useRequest, useSetState } from 'ahooks';
import { findByPicturePageList } from '@/services/ant-design-pro/pictures';
import { paginationTool } from '@/utils/util';
import './MyUpload.less';

import defaultImage from '@/assets/img/defalut.png';

const data = [
  {
    title: 'Title 1',
    id: -1,
  },
];
for (let i = 0; i < 31; i++) {
  // @ts-ignore
  data.push({
    title: 'Index ' + i,
    id: i,
  });
}
//
// const imageUri = "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png";
//
// const getBase64 = (img: RcFile, callback: (url: string) => void) => {
//   const reader = new FileReader ();
//   reader.addEventListener ( 'load', () => callback ( reader.result as string ) );
//   reader.readAsDataURL ( img );
// };



interface Props {
  onChange?: (event: number | string,url:string) => void;
  type?: number | 0;
  id?: number | undefined;
  url?: string | undefined;
  multis?: boolean | false;
  width?: number|0, height?: number | 0
}

let nameSiteMapping = new Map();
nameSiteMapping.set(0, { id: 0, url: '' });
//findByPicturePageList
const MyUpload: React.FC<Props> = (props) => {
  const { onChange, id, url, multis, type,width,height } = props;
  const [open, setOpen] = useState(false);
  const [multi, setMulti] = useState(multis);
  const [isType, setIsType] = useState(type);
  const [multiItems, setMultiItems] = useSetState<API.Picture[]>([]);
  const [multiIds, setMultiIds] = useSetState<number[]>([]);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>(id > 0 ? url : defaultImage);

  const {
    run: fetchByPageList,
    refresh,
    data: dataList,
    loading: loading1,
  } = useRequest(findByPicturePageList, {
    debounceWait: 100,
    manual: true,
  });
  // fetchByPageList ();
  useMount(() => {
    //  fetchByPageList ( {type: type} );
  });


  const beforeUpload =  (file: RcFile) => {

    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error ( 'You can only upload JPG/PNG file!' );
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error ( 'Image must smaller than 2MB!' );
    }

      return isJpgOrPng && isLt2M;

  };

  const beforeUploadMedia =  (file: RcFile) => {
console.log(file)
    const isJpgOrPng = file.type === 'video/mp4' || file.type === 'video/avi';
    if (!isJpgOrPng) {
      message.error ( 'You can only upload MP4/AVI file!' );
    }
    const isLt2M = file.size / 1024 / 1024 < 100;
    if (!isLt2M) {
      message.error ( 'Image must smaller than 100MB!' );
    }

    return isJpgOrPng && isLt2M;

  };
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log('handleChange', info);

    if (info.file.status === 'uploading') {
      // @ts-ignore
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // @ts-ignore
      fetchByPageList({ type: type });
     setLoading(false);

      // Get this url from response in real world.
      // getBase64 ( info.file.originFileObj as RcFile, url => {
      //   setLoading ( false );
      // //  setImageUrl ( url );
      //

      // } );
    }
  };
  const [pagination, setPagination] = useState<API.Pagination>({
    page: 0,
    pageSize: 24,
  });
  const openDialog = () => {
    fetchByPageList({ type: type });
    setOpen(true);
  };
  const selectedImage = (item: API.Picture) => {
    console.log(item);
    if (multi) {
      console.log(item);
      let newVar = nameSiteMapping.has(item?.id);
      if (newVar) {
        nameSiteMapping.delete(item?.id);
      } else {
        nameSiteMapping.set(item.id, item);
      }
      console.log('MapLength: ' + nameSiteMapping.size);
      let itemmmid: number[] = [];
      let itemmm: API.Picture[] = [];
      nameSiteMapping.forEach((value: API.Picture, key: number) => {
        if (key != 0) {
          itemmmid.push(key);
          console.log(value);
          itemmm.push({ url: value.url, id: value.id });
        }
      });
      setMultiItems(itemmm);
      setMultiIds(itemmmid);


      /*      let itemmmid = []
            // 迭代 Map 中的 key
            for (let key of nameSiteMapping.keys ()) {
              console.log(key)
              itemmmid.push ( key )
            }
            setMultiIds ( itemmmid )
            let itemmm = []
            // 迭代 Map 中的 key
            for (let key of nameSiteMapping.values ()) {
              console.log(key)
              itemmm.push ( key )
              //  setMultiItem(nameSiteMapping.values());
            }
            console.log ( "setMultiItem", itemmm )
            setMultiItem ( itemmm )*/
    } else {
      if (onChange != null) {
        onChange(item?.id,item?.url);
      }

      // @ts-ignore
      setImageUrl(item?.url);

      setOpen(false);
    }
  };
  const selectedImages = () => {
    if (onChange != null) {
      let a = [];
      for (const aKey in multiIds) {
        let num = multiIds[aKey];
        a.push(num);
      }
      console.log('onDataSourceChange', a.join(','));
      let event = a.join(',');
      onChange(event);
      setOpen(false);
    }
  };
  const selectedImageRemove = (item: API.Picture) => {
    console.log(item);
    if (multi) {
      nameSiteMapping.delete(item?.id);

      console.log('MapLength: ' + nameSiteMapping.size);
      let itemmmid: number[] = [];
      let itemmm: API.Picture[] = [];
      nameSiteMapping.forEach((value: API.Picture, key: number) => {
        if (key != 0) {
          itemmmid.push(key);
          console.log(value);
          itemmm.push({ url: value.url, id: value.id });
        }
      });
      setMultiItems(itemmm);
      setMultiIds(itemmmid);
    }
  };
  const uploadButton = (
    <Button loading={loading} icon={<UploadOutlined />}>
      图片上传
    </Button>
  );
  const getStyleClassName = (item: API.Picture) => {
    let b1 = nameSiteMapping.get(item.id);

    console.log('getStyleClassName', b1);
    return b1 ? 'imageActive' : '';
  };
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  return (
    <div>
      {multi ? (
        <List
          grid={{ column: 4 }}
          dataSource={nameSiteMapping.values()}
          renderItem={(item: API.Picture) => (
            <List.Item>
              {item.id == 0 ? (
                <Image
                  width={100}
                  height={100}
                  preview={false}
                  src={item.url}
                  fallback={defaultImage}
                  onClick={() => openDialog()}
                />
              ) : (
                <Popconfirm title="删除确定吗？" onConfirm={() => selectedImageRemove(item)}>
                  {' '}
                  <Image
                    width={100}
                    height={100}
                    preview={false}
                    src={item.url}
                    fallback={defaultImage}
                  />
                </Popconfirm>
              )}
            </List.Item>
          )}
        ></List>
      ) : (
        type==2?<video poster={defaultImage} src={imageUrl} className={"video"}  onClick={() => openDialog()}></video>:<Image
          width={100}
          height={100}
          preview={false}
          src={imageUrl}
          fallback={defaultImage}
          onClick={() => openDialog()}
        />
      )}

      <Modal
        visible={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        width={1000}
        closable={false}
        footer={null}
      >
        <div>
          <List
            loading={loading1}
            pagination={paginationTool(
              pagination,
              dataList?.data?.total,
              (data1: API.Pagination) => {
                setPagination(data1);
                // @ts-ignore
                fetchByPageList({ type: isType, ...pagination });
              },
            )}
            grid={{
              gutter: 10,
              column: 8,
            }}
            header={
              <Space>
                {type == 1 || type == 4 || type == 5  || type == 6? (
                  <div>
                    <Upload
                  accept="jpg,png,jpeg"
                      name="file"
                      className="avatar-uploader"
                      showUploadList={false}
                      action={"/api/upload/image?type="+type}
                      beforeUpload={beforeUpload}
                      onChange={handleChange}
                    >
                      {uploadButton}
                    </Upload>
                    <Popconfirm title={<Input></Input>}>
                      <Button>图片地址</Button>
                    </Popconfirm>
                  </div>
                ) : (
                  ''
                )}

                {type == 2 ? (
                  <Space>
                    <Upload
                      accept="mp4,avi"
                      name="file"
                      className="avatar-uploader"
                      showUploadList={false}
                      action={"/api/upload/video?type="+type}
                      beforeUpload={beforeUploadMedia}
                      onChange={handleChange}
                    >
                      <Button loading={loading} icon={<UploadOutlined />}>
                        视频上传
                      </Button>
                    </Upload>

                  <Popconfirm title={<Input></Input>}>
                    <Button>视频地址</Button>
                  </Popconfirm>
                  </Space>
                ) : (
                  ''
                )}
                {type == 3 ? (
                  <Popconfirm title={<Input></Input>}>
                    <Button>音乐地址</Button>
                  </Popconfirm>
                ) : (
                  ''
                )}
                {multis ? (
                  <Button disabled={multiIds.length <= 0} onClick={selectedImages}>
                    选择确认
                  </Button>
                ) : (
                  ''
                )}
              </Space>
            }
            dataSource={dataList?.data?.list}
            renderItem={(item: API.Picture) => (
              <List.Item>
                <div className={getStyleClassName(item)}>
                  {item.istype ==2?<video className="video" src={item?.url}      onClick={() => selectedImage(item)}/>:<Image
                    width={100}
                    height={100}
                    preview={false}
                    src={item?.url}
                    onClick={() => selectedImage(item)}
                  />}
                 <div>
                   <p>{item.name}</p>
                   {/* <DeleteOutlined />*/}
                  </div>
                </div>
              </List.Item>
            )}
          />
        </div>
      </Modal>
    </div>
  );
};
export default MyUpload;
